package hu.bme.mit.bpel.incquery.validation.actions;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.viatra2.emf.incquery.runtime.exception.IncQueryRuntimeException;
import org.eclipse.viatra2.emf.incquery.validation.ui.editorlink.EditorBoundValidation;

public class InitValidationActionDelegate implements IEditorActionDelegate {

	IEditorPart currentEditor;
	
	@Override
	public void run(IAction action) {
		
		// Beautiful and concise code to invoke BPELMultipageEditorPart.getProcess() on this.currentEditor		
		try {
			EObject process = (EObject)(currentEditor.getClass().getMethod("getProcess").invoke(currentEditor));
			try {
				EditorBoundValidation.INSTANCE.initializeValidatorsOnEditor(currentEditor, process);
			} catch (IncQueryRuntimeException e) {
				e.printStackTrace();
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub

	}

	
//	boolean partlistenerRegistered = false;
	
	@Override
	public void setActiveEditor(IAction action, IEditorPart targetEditor) {

		this.currentEditor = targetEditor;
//		if (!partlistenerRegistered) {
//			registerPartListener(targetEditor);
//			partlistenerRegistered = true;
//		}
	}

//	private void registerPartListener(IEditorPart targetEditor) {
//			targetEditor.getEditorSite().getPage().addPartListener(new IPartListener2() {
//			
//			@Override
//			public void partVisible(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partOpened(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partInputChanged(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partHidden(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partDeactivated(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partClosed(IWorkbenchPartReference partRef) {
//				IWorkbenchPart part = partRef.getPart(false);
//				if (activeEditorRoots.keySet().contains(part)) {
//					EObject emfRoot = activeEditorRoots.get(part);
//					IFile file = activeEditorFiles.get(part);
//					ValidationUtil.closeValidators(emfRoot, file);
//					activeEditorRoots.remove(part);
//					activeEditorFiles.remove(part);
//				}
//			}
//			
//			@Override
//			public void partBroughtToTop(IWorkbenchPartReference partRef) { }
//			
//			@Override
//			public void partActivated(IWorkbenchPartReference partRef) { }
//		});
//
//	}

}
